package cz.pproproj.aaservice.guimodule.rest;

import cz.pproproj.aaservice.guimodule.BLLModuleAccess;
import cz.pproproj.aaservice.guimodule.auth.UserInfo;
import cz.pproproj.aaservice.guimodule.config.AuthService;
import cz.pproproj.aaservice.guimodule.model.AuthorizationUser;
import cz.pproproj.aaservice.guimodule.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;


@RestController
public class AuthenticationResource {

    private static final AuthHeaderParser AUTH_HEADER_PARSER = new AuthHeaderParser();
    @Autowired
    private AuthService authService;

    private BLLModuleAccess _bllModuleAccess = new AnnotationConfigApplicationContext("cz.pproproj.aaservice.aasbllmodule").getBean(BLLModuleAccess.class);

    @RequestMapping(method = RequestMethod.GET,
            value = "/authentication/{moduleName}",
            consumes = "*/*",
            produces = "application/json")
    public UserInfo authenticate( @RequestHeader HttpHeaders headers, @PathVariable String moduleName) throws Exception{
        AuthService.UserTokens userTokens = authService.authenticate(AUTH_HEADER_PARSER.parse(headers), moduleName);
        return new UserInfo(userTokens);
    }


    @RequestMapping(method = RequestMethod.GET,
            value = "/token-invalidation",
            consumes = "*/*",
            produces = "application/json")
    public MessageResponse invalidateTokens(
            @RequestHeader HttpHeaders headers) throws Exception{
        authService.invalidateTokens(AUTH_HEADER_PARSER.parse(headers));
        return new MessageResponse("Tokens successfully invalidated");
    }


    @RequestMapping(method = RequestMethod.GET,
            value = "/token-refresh",
            consumes = "*/*",
            produces = "application/json")
    public UserInfo refreshTokens(
            @RequestParam(required = true, value = "token") String refreshToken) throws Exception{
        AuthService.UserTokens userTokens = authService.refresh(refreshToken);
        return new UserInfo(userTokens);
    }


    @RequestMapping(method = RequestMethod.GET,
            value = "/authorization",
            produces = "application/json")
    public MessageResponse authorize(
            @RequestParam(required = true, value = "role") String neededRole,
            @RequestHeader HttpHeaders headers) throws Exception{
        User user = authService.authenticate(AUTH_HEADER_PARSER.parse(headers), null).getUser();
        boolean ok = _bllModuleAccess.authorize(new AuthorizationUser(user.name, null), null);
        if (ok) {
            return new MessageResponse("User is authorized for role " + neededRole + " .");
        } else {
            throw new Exception();
        }
    }
}
